package com.ruyuan.authorization;

import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xx
 */
public class MyModularRealmAuthorizer extends ModularRealmAuthorizer {

    @Override
    public boolean hasRole(PrincipalCollection principals, String roleIdentifier) {
        assertRealmsConfigured();
        Map<String, Realm> realmMap = getRealms().stream().collect(Collectors.toMap(Realm::getName, it -> it));
        for (String realmName : principals.getRealmNames()) {
            Realm realm = realmMap.get(realmName);
            if (!(realm instanceof Authorizer)) {
                continue;
            }
            if (((Authorizer) realm).hasRole(principals, roleIdentifier)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean isPermitted(PrincipalCollection principals, String permission) {
        assertRealmsConfigured();
        Map<String, Realm> realmMap = getRealms().stream().collect(Collectors.toMap(Realm::getName, it -> it));
        for (String realmName : principals.getRealmNames()) {
            Realm realm = realmMap.get(realmName);
            if (!(realm instanceof Authorizer)) {
                continue;
            }
            if (((Authorizer) realm).isPermitted(principals, permission)) {
                return true;
            }
        }
        return false;
    }
}

